package cloud.maque.module.system.extend.impl;

import cloud.maque.module.system.entity.SysDept;
import cloud.maque.module.system.extend.DeptExtendService;
import cloud.maque.module.system.model.DeptDto;
import cloud.maque.module.system.service.DeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptExtendServiceImpl implements DeptExtendService {

    @Autowired
    DeptService deptService;

    @Override
    public List<DeptDto> GetDeptList(SysDept data) {
        List<SysDept> list = deptService.GetList(data);

        // 将所有部门转换为DeptDto
        List<DeptDto> deptDtoList = list.stream().map(dept -> {
            DeptDto dto = new DeptDto();
            BeanUtils.copyProperties(dept, dto);
            return dto;
        }).collect(Collectors.toList());

        // 获取顶级部门并构建树
        return buildDeptTree(deptDtoList, "");
    }

    /**
     * 递归构建部门树
     *
     * @param deptList 部门列表
     * @param parentId 父部门ID
     * @return 构建好的树形结构
     */
    private List<DeptDto> buildDeptTree(List<DeptDto> deptList, String parentId) {
        return deptList.stream()
                .filter(dept -> dept.getParentId().equals(parentId))
                .map(dept -> {
                    dept.setChildren(buildDeptTree(deptList, dept.getDeptId()));
                    return dept;
                })
                .collect(Collectors.toList());
    }
}
